package com.quicklife.service.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.quicklife.service.inter.FileUploadService;
import com.quicklife.util.StringUtil;

/**
 * 处理上传的信息中包含文件
 * 
 * @author HackerD
 * 
 */
public class FileUploadServiceImpl implements FileUploadService {
	// 保存取出的文件,信息验证成功后才保存到硬盘
	private Map<String, FileItem> tempFileItem = new HashMap<String, FileItem>();
	// 临时目录
	private String temp;
	// 上传文件存放目录
	private String loadpath;
	// 保存的文件名称
	private String fileName;

	@Override
	public String getUploadInfos(HttpServletRequest request) {
		// 保存取出的信息
		JSONObject jsonObject = new JSONObject();
		try {
			// 临时目录
			temp = request.getSession().getServletContext().getRealPath("/")
					+ "upload";
			// 上传文件存放目录
			loadpath = request.getSession().getServletContext()
					.getRealPath("/")
					+ "upload";
			// 判断该路径是否存在，不存在就创建
			File tempFile = new File(temp);
			if (!tempFile.exists()) {
				tempFile.mkdirs();
			}
			DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
			fileItemFactory.setSizeThreshold(1024 * 1024);// 设置最多只允许在内存中存储的数据,单位:字节
			fileItemFactory.setRepository(tempFile);// 设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录
			ServletFileUpload servletFileUpload = new ServletFileUpload(
					fileItemFactory);
			String userAgent = request.getHeader("user-agent").toLowerCase();
			if (userAgent.contains("android")) {
				servletFileUpload.setHeaderEncoding("ISO8859_1");
			} else {
				servletFileUpload.setHeaderEncoding("UTF-8");
			}

			// Enumeration<String> keys = request.getHeaderNames();
			// String key = null;
			// while (keys.hasMoreElements()) {
			// key = keys.nextElement();
			// System.out.println(key+"----------"+request.getHeader("user-agent"));
			// }
			// servletFileUpload.setSizeMax(sizeMax)// 设置允许用户上传文件大小,单位:字节

			// 开始读取上传信息
			List<FileItem> fileItems = servletFileUpload.parseRequest(request);
			Iterator<FileItem> iter = fileItems.iterator(); // 依次处理每个上传的文件
			while (iter.hasNext()) {
				FileItem item = iter.next();// 忽略其他不是文件域的所有表单信息
				if (!item.isFormField()) {
					String name = item.getName();// 获取上传文件名,包括路径
					long size = item.getSize();
					if ((name == null || "".equals(name)) && size == 0) {
						continue;
					}

					int point = name.indexOf(".");
					name = StringUtil.getUUID()
							+ name.substring(point, name.length());
					fileName = name;
					tempFileItem.put(name, item);
					jsonObject.put(item.getFieldName(), request.getSession()
							.getServletContext().getContextPath()
							+ "/upload/" + name);

				} else// 取出不是文件域的所有表单信息
				{
					// String fieldvalue = item.getString();
					// 如果包含中文应写为：(转为UTF-8编码)
					if (userAgent.contains("android")) {
						jsonObject.put(item.getFieldName(), new String(item
								.getString().getBytes("ISO8859_1"), "UTF-8"));
					} else {
						jsonObject.put(item.getFieldName(),
								item.getString("utf-8"));
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return jsonObject.toString();
	}

	@Override
	public String saveFile() {
		try {
			if (!tempFileItem.isEmpty()) {
				for (Entry<String, FileItem> entry : tempFileItem.entrySet()) {
					File fNew = new File(loadpath, entry.getKey());
					entry.getValue().write(fNew);
				}

			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

}
